<template>
  <el-breadcrumb
    class="app-breadcremb"
    separator="/"
  >
    <transition-group name="breadcrumb">
      <el-breadcrumb-item
        v-for="(item, index) in levelList"
        :key="item.path"
      >
        <span
          v-if="item.redirect === 'noRedirect' || index == levelList.length - 1"
          class="no-redirect"
        >{{ item.meta.title }}</span>
        <a
          v-else
          @click.prevent="handleLink(item)"
        >{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { compile } from 'path-to-regexp'
import { useRoute, useRouter, RouteLocationMatched } from 'vue-router'

const levelList = ref<RouteLocationMatched[]>([])
const route = useRoute()
const router = useRouter()

const isDashboard = (route:any):Boolean => {
  const name:string = route && route.name
  if (!name) {
    return false
  }
  const isDashboard = name.trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase()
  return isDashboard
}

// 获取面包屑
const getBreadcrumb = () => {
  // 只展示路由中设置了meta.title的元素；
  let matched:RouteLocationMatched[] = route.matched.filter((item) => item.meta && item.meta.title)
  const first = matched[0]

  if (!isDashboard(first)) {
    const route:any[] = [{ path: '/dashboard', meta: { title: 'Dashboard' } }]
    matched = route.concat(matched)
  }

  levelList.value = matched.filter((item) => item.meta && item.meta.title)
}

const pathCompile = (path: string) => {
  const { params } = route
  const toPath = compile(path)
  return toPath(params)
}

const handleLink = (item:any) => {
  const { redirect, path } = item
  if (redirect) {
    router.push(redirect)
  }
  router.push(pathCompile(path))
}

onMounted(() => {
  getBreadcrumb()
})

watch(route, () => {
  getBreadcrumb()
})
</script>

<style lang="scss" scoped>
.navbar .breadcrumb-container {
  display: inline-block;
  font-size: 14px;
  line-height: 56px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
